/**
 * FileUtil.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-11-21 18:32:45 +0800 $
 * $Revision: 1227 $
 */
package com.myspace.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.log4j.Logger;

/**
 *
 * @author AllenChen
 *
 */
public class FileUtil {

	private static Logger LOG = Logger.getLogger(FileUtil.class);

	public static void unzipFile(String zipFile, String toDir) {
		ZipInputStream zis = null;
		BufferedOutputStream bos = null;
		try {
			File dirPath = new File(toDir);
			if (!dirPath.exists() && !dirPath.mkdirs()) {
				throw new IOException("java.lang.IOException: " + toDir
						+ " (Unable to create directory)");
			}
			File file = null;
			ZipEntry entry = null;
			zis = new ZipInputStream(new BufferedInputStream(
					new FileInputStream(zipFile)));
			while ((entry = zis.getNextEntry()) != null) {
				if (entry.isDirectory()) {
					file = new File(toDir + File.separator + entry.getName());
					if (!file.exists() && !file.mkdirs()) {
						throw new IOException("java.lang.IOException: "
								+ file.getPath()
								+ " (Unable to create directory)");
					}
				} else {
					file = new File(toDir + File.separator + entry.getName());
					if (!file.getParentFile().exists()
							&& !file.getParentFile().mkdirs()) {
						throw new IOException("java.lang.IOException: "
								+ file.getParentFile().getPath()
								+ " (Unable to create directory)");
					}
					if (!file.exists() && !file.createNewFile()) {
						throw new IOException("java.lang.IOException: "
								+ file.getPath() + " (Unable to create file)");
					}
					bos = new BufferedOutputStream(new FileOutputStream(file));
					byte[] buf = new byte[1024];
					int len;
					while ((len = zis.read(buf)) > 0) {
						bos.write(buf, 0, len);
					}
					bos.flush();
				}
			}
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				zis.close();
				bos.close();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
	}

	public static void writeFile(String dir, String fileName, String content) {
		BufferedWriter writer = null;
		try {
			File file = new File(dir + File.separator + fileName);
			if (!file.getParentFile().exists()
					&& !file.getParentFile().mkdirs()) {
				throw new IOException("java.lang.IOException: " + dir
						+ " (Unable to create directory)");
			}
			if (!file.exists() && !file.createNewFile()) {
				throw new IOException("java.lang.IOException: "
						+ file.getPath() + " (Unable to create file)");
			}
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(content);
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
	}

	public static void writeFile(File file, byte[] content) {
		if (file == null) {
			LOG.error("File is null");
		}

		BufferedOutputStream bos = null;
		try {
			if (!file.exists()) {
				file = createFile(file.getPath());
			}
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(content);
			bos.flush();
			LOG.info("Save file successfully, length =  " + content.length);
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				LOG.error(e);
			}
		}
	}

	public static String readFileAsString(String fileName) {
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			String str = null;
			reader = new BufferedReader(new FileReader(fileName));
			while ((str = reader.readLine()) != null) {
				buffer.append(str);
			}
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
		return buffer.toString();
	}

	public static String readFileAsString(InputStream inputStream) {
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			String str = null;
			reader = new BufferedReader(new InputStreamReader(inputStream));
			while ((str = reader.readLine()) != null) {
				buffer.append(str);
			}
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
		return buffer.toString();
	}

	public static byte[] readFileAsBytes(String fileName) {
		if (fileName == null || !(new File(fileName)).exists())
			return null;
		ByteArrayOutputStream bos = null;
		BufferedInputStream bis = null;
		byte[] buffer = new byte[1024];
		byte[] ret = null;
		try {
			bos = new ByteArrayOutputStream();
			bis = new BufferedInputStream(new FileInputStream(
					new File(fileName)));
			while (bis.available() > 0) {
				bis.read(buffer);
				bos.write(buffer);
			}
			ret = bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static File createFile(String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
			throw new IOException("java.lang.IOException: "
					+ file.getParentFile() + " (Unable to create directory)");
		}
		if (!file.exists() && !file.createNewFile()) {
			throw new IOException("java.lang.IOException: " + file.getPath()
					+ " (Unable to create file)");
		}
		return file;
	}

	public static void writeToFile(InputStream is, File filePath) {
		int bytesRead = 0;
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			if (is != null && filePath != null && filePath.exists()) {
				bis = new BufferedInputStream(is);
				bos = new BufferedOutputStream(new FileOutputStream(filePath));
				while ((bytesRead = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, bytesRead);
				}
			}
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			try {
				if (bis != null)
					bis.close();
			} catch (Exception e) {
				LOG.error(e);
			}
			try {
				if (bos != null)
					bos.close();
			} catch (Exception e) {
				LOG.error(e);
			}

		}
	}

}
